package com.jvtd.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jvtd.bean.ProvincesBean;
import com.jvtd.rxjava.JvtdObserverSubscriber;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 省市区数据
 *
 * @author Chenlei
 * created at 2018/9/18
 **/
public class ProvincesUtils {
    private static final String PROVINCES_NAME = "provinces.json";

    private static final String CHINA_LEVEL = "0";
    private static final String PROVINCE_LEVEL = "1";
    private static final String CITY_LEVEL = "2";
    private static final String AREA_LEVEL = "3";

    public static final String BJ_ID = "110000";//北京
    public static final String TJ_ID = "120000";//天津
    public static final String HE_ID = "130000";//河北
    public static final String SX_ID = "140000";//山西
    public static final String NM_ID = "150000";//内蒙古
    public static final String LN_ID = "210000";//辽宁
    public static final String JL_ID = "220000";//吉林
    public static final String HL_ID = "230000";//黑龙江
    public static final String SH_ID = "310000";//上海
    public static final String JS_ID = "320000";//江苏
    public static final String ZJ_ID = "330000";//浙江
    public static final String AH_ID = "340000";//安徽
    public static final String FJ_ID = "350000";//福建
    public static final String JX_ID = "360000";//江西
    public static final String SD_ID = "370000";//山东
    public static final String HA_ID = "410000";//河南
    public static final String HB_ID = "420000";//河北
    public static final String HN_ID = "430000";//湖南
    public static final String GD_ID = "440000";//广东
    public static final String GX_ID = "450000";//广西
    public static final String HI_ID = "460000";//海南
    public static final String CQ_ID = "500000";//重庆
    public static final String SC_ID = "510000";//四川
    public static final String GZ_ID = "520000";//贵州
    public static final String YN_ID = "530000";//云南
    public static final String XZ_ID = "540000";//西藏
    public static final String SN_ID = "610000";//陕西
    public static final String GS_ID = "620000";//甘肃
    public static final String QH_ID = "630000";//青海
    public static final String NX_ID = "640000";//宁夏
    public static final String XJ_ID = "650000";//新疆
    public static final String TW_ID = "710000";//台湾
    public static final String HK_ID = "810000";//香港
    public static final String MO_ID = "820000";//澳门
    public static final String DYD_ID = "900000";//钓鱼岛

    private static final List<String> WIPEOFF_DYD = Collections.singletonList(DYD_ID);//去除钓鱼岛
    private static final List<String> WIFEOFF_GHT = Arrays.asList(TW_ID, HK_ID, MO_ID, DYD_ID);//去除港澳台

    private static volatile ProvincesUtils instance;
    private final Context mContext;

    private ProvincesBean mChinaBean;
    private List<ProvincesBean> mProvincesBeans;
    private List<List<ProvincesBean>> mCityBeans;
    private List<List<List<ProvincesBean>>> mAreaBeans;
    private boolean isCreate = false;
    private boolean isMunicipal = false;

    private List<String> mWipeOffProvinces = new ArrayList<>(WIPEOFF_DYD);
    private boolean isUpdate = false;

    public interface OnObtainListener {
        void onObtainSuccess(List<ProvincesBean> provincesBeans, List<List<ProvincesBean>> cityBeans, List<List<List<ProvincesBean>>> areaBeans);

        void onObtainFailed();
    }

    public static ProvincesUtils getInstance(Context context) {
        if (instance == null)
            synchronized (ProvincesUtils.class) {
                if (instance == null)
                    instance = new ProvincesUtils(context.getApplicationContext());
            }
        return instance;
    }

    private ProvincesUtils(Context context) {
        mContext = context;
    }

    public List<ProvincesBean> getProvincesBeans() {
        return mProvincesBeans;
    }

    public List<List<ProvincesBean>> getCityBeans() {
        return mCityBeans;
    }

    public List<List<List<ProvincesBean>>> getAreaBeans() {
        return mAreaBeans;
    }

    public boolean isCreate() {
        return isCreate;
    }

    //去除一些地区
    public ProvincesUtils wipeOffProvinces(List<String> wipeOffProvincesBeans) {
        this.mWipeOffProvinces = wipeOffProvincesBeans == null ? new ArrayList<>() : wipeOffProvincesBeans;
        this.isUpdate = true;
        return this;
    }

    //开启二级模式  直辖市下直接为区 三级不可使用 如使用则报错
    public ProvincesUtils setMunicipal(boolean isMunicipal){
        if (this.isMunicipal != isMunicipal){
            this.isMunicipal = isMunicipal;
            this.isUpdate = true;
        }
        return this;
    }

    private boolean isWipeOffProvince(String id) {
        for (String wipeOffProvince : mWipeOffProvinces) {
            if (TextUtils.equals(wipeOffProvince, id))
                return true;
        }
        return false;
    }

    @SuppressLint("CheckResult")
    public void getProvincesData(OnObtainListener onObtainListener) {
        if (mProvincesBeans != null
                && mProvincesBeans.size() > 0
                && mCityBeans != null
                && mCityBeans.size() > 0
                && mAreaBeans != null
                && mAreaBeans.size() > 0
                && !isUpdate) {
            if (onObtainListener != null)
                onObtainListener.onObtainSuccess(mProvincesBeans, mCityBeans, mAreaBeans);
            return;
        }
        isUpdate = false;
        mProvincesBeans = new ArrayList<>();
        mCityBeans = new ArrayList<>();
        mAreaBeans = new ArrayList<>();
        Observable.fromCallable(() -> {
            Boolean b = false;
            String JsonData = FileUtils.getJson(mContext, PROVINCES_NAME);//获取assets目录下的json文件数据

            try {
                List<ProvincesBean> provincesBeans = new ArrayList<>();//所有省份
                List<ProvincesBean> cityBeans = new ArrayList<>();//所有市级
                List<ProvincesBean> areaBeans = new ArrayList<>();//所有区级

                ArrayList<ProvincesBean> jsonBeans = new Gson().fromJson(JsonData, new TypeToken<List<ProvincesBean>>() {
                }.getType());
                //分离省市区
                for (ProvincesBean jsonBean : jsonBeans) {
                    if (TextUtils.equals(jsonBean.getLevelType(), PROVINCE_LEVEL) && !isWipeOffProvince(jsonBean.getID())) {
                        provincesBeans.add(jsonBean);
                    } else if (TextUtils.equals(jsonBean.getLevelType(), CITY_LEVEL)) {
                        cityBeans.add(jsonBean);
                    } else if (TextUtils.equals(jsonBean.getLevelType(), AREA_LEVEL)) {
                        areaBeans.add(jsonBean);
                    }
                }
                //省份排序
                mProvincesBeans = provincesBeans;
//                Collections.sort(mProvincesBeans, (lhs, rhs) -> {
//                    //根据拼音进行排序
//                    return lhs.getPinyin().compareTo(rhs.getPinyin());
//                });

                //根据省份获取其他
                for (ProvincesBean provincesBean : mProvincesBeans) {//循环添加省份
                    String provincesID = provincesBean.getID();//省份ID
                    List<ProvincesBean> oneProvincesCityBeans = new ArrayList<>();//一个省份下所有城市
                    List<List<ProvincesBean>> oneProvincesAreaBeans = new ArrayList<>();//一个省份下一个城市的所有区
                    for (int i = 0; i < cityBeans.size(); i++) {//循环添加省份下所有城市
                        ProvincesBean cityBean = cityBeans.get(i);
                        String cityID = cityBean.getID();
                        if (TextUtils.equals(cityBean.getParentId(), provincesID)) {//循环添加城市下所有区
                            List<ProvincesBean> oneCityAreaBeans = new ArrayList<>();
                            oneProvincesCityBeans.add(cityBean);
                            for (int i1 = 0; i1 < areaBeans.size(); i1++) {
                                ProvincesBean areaBean = areaBeans.get(i1);
                                if (TextUtils.equals(areaBean.getParentId(), cityID)) {
                                    oneCityAreaBeans.add(areaBean);
                                    areaBeans.remove(i1);
                                    i1--;
                                }
                            }
                            oneProvincesAreaBeans.add(oneCityAreaBeans);
                            cityBeans.remove(i);
                            i--;
                        }
                    }
                    mCityBeans.add(oneProvincesCityBeans);
                    mAreaBeans.add(oneProvincesAreaBeans);
                }

                //直辖市区级转市级  二级结构
                if (isMunicipal){
                    List<List<ProvincesBean>> tempBeans = new ArrayList<>();
                    for (int i = 0; i < mCityBeans.size(); i++) {
                        List<ProvincesBean> cBeans = mCityBeans.get(i);
                        boolean replace = false;
                        int replaceIndex = 0;
                        String pId = "";
                        for (int j = 0; j < cBeans.size(); j++) {
                            ProvincesBean bean = cBeans.get(j);
                            if (TextUtils.equals(bean.getParentId(), ProvincesUtils.BJ_ID) ||
                                    TextUtils.equals(bean.getParentId(), ProvincesUtils.TJ_ID) ||
                                    TextUtils.equals(bean.getParentId(), ProvincesUtils.SH_ID) ||
                                    TextUtils.equals(bean.getParentId(), ProvincesUtils.CQ_ID)){{
                                replace = true;
                                replaceIndex = j;
                                pId = bean.getParentId();
                                break;
                            }}
                        }
                        if (replace){
                            List<ProvincesBean> pBeans = new ArrayList<>();
                            for (ProvincesBean provincesBean : mAreaBeans.get(i).get(replaceIndex)) {
                                provincesBean.setParentId(pId);
                                pBeans.add(provincesBean);
                            }
                            tempBeans.add(pBeans);
                        }else {
                            tempBeans.add(cBeans);
                        }
                    }

                    mCityBeans = tempBeans;
                }

                b = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return b;
        }).compose(upstream -> upstream.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()))
                .subscribe(new JvtdObserverSubscriber<Boolean>(null) {
                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (onObtainListener != null)
                            if (aBoolean) {
                                isCreate = true;
                                onObtainListener.onObtainSuccess(mProvincesBeans, mCityBeans, mAreaBeans);
                            } else {
                                isCreate = false;
                                onObtainListener.onObtainFailed();
                            }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (onObtainListener != null) {
                            isCreate = false;
                            onObtainListener.onObtainFailed();
                        }
                    }
                });
    }
}
